package com.ruoyi.store.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.UploadUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.vo.UpFileResultVo;
import com.ruoyi.store.service.IHmSystemAttachmentService;
import com.ruoyi.store.service.IHmSystemConfigService;
import com.ruoyi.store.service.UploadService;

import com.ruoyi.store.vo.FileResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UploadServiceImpl implements UploadService {
	@Autowired
	private IHmSystemConfigService systemConfigService;

	@Autowired
	private IHmSystemAttachmentService systemAttachmentService;

	/**
	 * 图片上传
	 * @param multipart MultipartFile 上传文件流
	 * @param model String 上传模块
	 */
	@Override
	public FileResultVo image(MultipartFile multipart, String model, Integer pid) throws IOException {
		setImageUpload(model);
		UpFileResultVo upfile = UploadUtil.file(multipart);
		FileResultVo file = new FileResultVo();
		BeanUtils.copyProperties(upfile,file);
		//文件入库
		file.setType(file.getType().replace("image/", ""));
		systemAttachmentService.create(file, pid);
		return file;
	}

	/**
	 * 图片文件
	 * @param multipart MultipartFile 上传文件流
	 * @param model String 上传模块
	 */
	@Override
	public FileResultVo file(MultipartFile multipart, String model, Integer pid) throws IOException {
		setFileUpload(model);
		UpFileResultVo upfile = UploadUtil.file(multipart);
		FileResultVo file = new FileResultVo();
		BeanUtils.copyProperties(upfile,file);
		//文件入库
		file.setType(file.getType().replace("file/", ""));
		systemAttachmentService.create(file, pid);
		return file;
	}

	/**
	 * 设置上传图片参数
	 * @param model String 上传模块
	 */
	private void setImageUpload(String model){
		UploadUtil.setRootPath(systemConfigService.getValueByKey(Constants.UPLOAD_ROOT_PATH_CONFIG_KEY));
		UploadUtil.setModelPath(model);
		UploadUtil.setExtStr(systemConfigService.getValueByKey(Constants.UPLOAD_IMAGE_EXT_STR_CONFIG_KEY));
		UploadUtil.setSize(Integer.parseInt(systemConfigService.getValueByKey(Constants.UPLOAD_IMAGE_MAX_SIZE_CONFIG_KEY)));
		UploadUtil.setType(Constants.UPLOAD_TYPE_IMAGE);
	}

	/**
	 * 设置上传文件参数
	 * @param model String 上传模块
	 */
	private void setFileUpload(String model){
		UploadUtil.setRootPath(systemConfigService.getValueByKey(Constants.UPLOAD_ROOT_PATH_CONFIG_KEY));
		UploadUtil.setModelPath(model);
		UploadUtil.setExtStr(systemConfigService.getValueByKey(Constants.UPLOAD_FILE_EXT_STR_CONFIG_KEY));
		UploadUtil.setSize(Integer.parseInt(systemConfigService.getValueByKey(Constants.UPLOAD_FILE_MAX_SIZE_CONFIG_KEY)));
		UploadUtil.setType(Constants.UPLOAD_TYPE_FILE);
	}
}
